<template>
	<view class="container">
		<!-- 固定区域 -->
		<view class="fixed-area">
			<!-- 顶部轮播图 -->
			<swiper class="banner-swiper" circular indicator-dots autoplay interval="3000" duration="500">
				<swiper-item v-for="(item, index) in bannerList" :key="index">
					<view class="banner-item">
						<image :src="item.imageUrl" mode="aspectFill" class="banner-image"></image>
						<view class="banner-title">
							<text class="banner-title-text">{{item.title}}</text>
							<text class="banner-subtitle">{{item.subtitle}}</text>
						</view>
					</view>
				</swiper-item>
			</swiper>

			<!-- 三个核心功能区块 -->
			<view class="feature-section">
				<view class="feature-item">
					<button @click="handleToJobPreference" class="feature-button">
						<view class="feature-icon job-icon">
							<view class="icon-wrapper">
								<text class="feature-emoji">🔍</text>
							</view>
						</view>
						<view class="feature-content">
							<text class="feature-title">岗位匹配</text>
							<text class="feature-desc">精准推荐岗位</text>
						</view>
					</button>
				</view>
				<view class="feature-item">
					<button @click="handleToJL" class="feature-button">
						<view class="feature-icon template-icon">
							<view class="icon-wrapper">
								<text class="feature-emoji">📝</text>
							</view>
						</view>
						<view class="feature-content">
							<text class="feature-title">简历精改</text>
							<text class="feature-desc">专业优化简历</text>
						</view>
					</button>
				</view>
				<view class="feature-item">
					<button @click="handleToFD" class="feature-button">
						<view class="feature-icon interview-icon">
							<view class="icon-wrapper">
								<text class="feature-emoji">🎯</text>
							</view>
						</view>
						<view class="feature-content">
							<text class="feature-title">笔面辅导</text>
							<text class="feature-desc">全方位笔面指导</text>
						</view>
					</button>
				</view>
			</view>

			<!-- 最新公告标题 -->
			<view class="section-header">
				<view class="section-title">最新公告</view>
				<view class="section-more" @tap="navigateTo('/pagesA/recruitNotice/index')">
					更多 <text class="iconfont icon-right"></text>
				</view>
			</view>
		</view>

		<!-- 可滚动内容区域 -->
		<view class="scrollable-content">
			<!-- 公告列表 -->
			<scroll-view scroll-y class="content-list" @scrolltolower="loadMoreNotices" refresher-enabled
				:refresher-triggered="isRefreshingNotices" @refresherrefresh="refreshNotices">
				<view class="notice-card" v-for="(item, index) in noticeList" :key="index"
					@tap="goToNoticeDetail(item)">
					<view class="notice-title">{{item.title}}</view>
					<view class="notice-info">
						<view class="notice-tags-row">
							<view class="notice-tags">
								<text class="notice-tag">{{getCompanyTypeText(item.companyType) || '暂无'}}</text>
								<text
									class="notice-tag">{{item.isWeave !== undefined ? (item.isWeave ? '带编' : '不带编') : '暂无'}}</text>
							</view>
							<text class="notice-status"
								:class="[getStatusClass(item.applyStatus)]">{{getStatusText(item.applyStatus)}}</text>
						</view>
						<view class="notice-detail">
							<text class="notice-detail-item">招聘人数：{{item.recruitNum || '暂无'}}</text>
							<text class="notice-detail-item">地址：{{item.address || '暂无'}}</text>
							<text
								class="notice-detail-item">报名时间：{{ item.startTime && item.endTime ? `${formatDate(item.startTime)} ~ ${formatDate(item.endTime)}` : '暂无' }}</text>
						</view>
					</view>
				</view>

				<!-- 加载更多提示 -->
				<view class="loading-more" v-if="noticeList.length > 0">
					<text v-if="isLoadingNotices">加载中...</text>
					<text v-else-if="!hasMoreNotices">没有更多公告了</text>
				</view>

				<!-- 空状态提示 -->
				<view class="empty-state" v-if="noticeList.length === 0 && !isLoadingNotices">
					<text class="empty-text">暂无公告信息</text>
				</view>
			</scroll-view>
		</view>
		<!-- 匹配动画组件，初始不显示 -->
		<match-animation v-if="showMatchAnimation" :visible="true" />
	</view>
</template>

<script>
	import {
		getRecruitNotice
	} from '@/api/notice/recruitNotice.js'
	import {
		getDicts
	} from '@/api/dict/data.js'
	import MatchAnimation from '@/components/match-animation/match-animation.vue'
	import config from '@/config'

	export default {
		components: {
			MatchAnimation
		},
		data() {
			return {
				statusBarHeight: 0,

				// 轮播图数据
				bannerList: [{
						id: 1,
						imageUrl: config.baseUrl + '/profile/upload/banner/gw.png',
						linkUrl: '/pages/job/index',
						title: '岗位匹配',
						subtitle: '精准推荐合适岗位'
					},
					{
						id: 2,
						imageUrl: config.baseUrl + '/profile/upload/banner/jl.png',
						linkUrl: '/pages/job/index',
						title: '简历精改',
						subtitle: '专业优化提升简历'
					},
					{
						id: 3,
						imageUrl: config.baseUrl + '/profile/upload/banner/bm.png',
						linkUrl: '/pages/job/index',
						title: '就业辅导',
						subtitle: '全方位就业辅导'
					}
				],

				// 公告列表数据
				noticeList: [],
				noticePageNum: 1,
				noticePageSize: 5, // 首页只显示3条最新公告
				totalNotices: 0,
				isLoadingNotices: false,
				isRefreshingNotices: false,
				hasMoreNotices: true,
				// 公司类型字典名称
				companyTypeDictType: 'recruit_company_type',
				// 公司类型字典
				companyTypeDict: [],
				// 学历要求字典名称
				degreeTypeDictType: 'recruit_degree',
				// 学历要求字典
				degreeTypeDict: [],
				// 报名状态字典名称
				applyStatusDictType: 'recruit_notice_status',
				// 报名状态字典
				applyStatusDict: [],
				showMatchAnimation: false
			}
		},
		onLoad() {
			// 获取状态栏高度，适配不同机型
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;

			// 加载字典数据
			this.loadDictData();

			// 初始加载数据
			this.fetchNoticeList();
		},
		methods: {
			handleToJL() {
				this.openWeChatCustomerService("https://work.weixin.qq.com/kfid/kfc240f656c37885d6f", "ww56168f25214ab777");
			},
			handleToFD() {
				this.openWeChatCustomerService("https://work.weixin.qq.com/kfid/kfc8f86f62c906c811f", "ww56168f25214ab777");
			},
			// 打开微信客服
			openWeChatCustomerService(
				weiXinCustomerServiceUrl = "",
				corpId = "",
				showMessageCard = false,
				sendMessageTitle = "",
				sendMessagePath = "",
				sendMessageImg = ""
			) {
				if (!weiXinCustomerServiceUrl || !corpId) {
					uni.showToast({
						title: "请配置好客服链接或者企业ID",
						icon: "none"
					});
					return;
				}

				// 微信小程序环境
				// #ifdef MP-WEIXIN
				try {
					wx.openCustomerServiceChat({
						extInfo: {
							url: weiXinCustomerServiceUrl, // 客服链接
						},
						corpId, // 企业ID
						showMessageCard, // 是否发送小程序气泡消息
						sendMessageTitle, // 气泡消息标题
						sendMessagePath, // 气泡消息小程序路径（需加上".html"）
						sendMessageImg, // 气泡消息图片
						success(res) {
							console.log("success", JSON.stringify(res));
						},
						fail(err) {
							console.log("fail", JSON.stringify(err));
							uni.showToast({
								title: err.errMsg,
								icon: "none"
							});
							// 失败时复制链接
							uni.setClipboardData({
								data: weiXinCustomerServiceUrl,
								success: () => {
									uni.showToast({
										title: '链接已复制，请在浏览器中打开',
										icon: 'none',
										duration: 2000
									});
								}
							});
						},
					});
				} catch (error) {
					console.error('openCustomerServiceChat error:', error);
					// 如果出错，复制链接
					uni.setClipboardData({
						data: weiXinCustomerServiceUrl,
						success: () => {
							uni.showToast({
								title: '链接已复制，请在浏览器中打开',
								icon: 'none',
								duration: 2000
							});
						}
					});
				}
				// #endif

				// H5环境
				// #ifdef H5
				window.open(weiXinCustomerServiceUrl, '_blank');
				// #endif
				
				// App环境
				// #ifdef APP-PLUS
				plus.runtime.openURL(weiXinCustomerServiceUrl);
				// #endif
				
				// 其他小程序环境
				// #ifdef MP && !MP-WEIXIN
				uni.setClipboardData({
					data: weiXinCustomerServiceUrl,
					success: () => {
						uni.showToast({
							title: '链接已复制，请在浏览器中打开',
							icon: 'none',
							duration: 2000
						});
					}
				});
				// #endif
			},
			// 岗位匹配跳转
			handleToJobPreference() {
				// 显示动画
				this.showMatchAnimation = true

				// 3秒后跳转并隐藏动画
				setTimeout(() => {
					// 先隐藏动画
					this.showMatchAnimation = false
					// 等待动画消失后再跳转
					setTimeout(() => {
						this.$tab.navigateTo('/pagesA/mine/suggest/index')
					}, 300)
				}, 3000)
			},
			// 页面导航
			navigateTo(url) {
				// 检查是否是 tabbar 页面
				if (url === '/pages/index' ||
					url === '/pages/job/index' ||
					url === '/pages/mine/index') {
					uni.switchTab({
						url: url
					});
				} else {
					uni.navigateTo({
						url: url
					});
				}
			},


			// 获取公告列表
			async fetchNoticeList(isRefresh = false) {
				if (this.isLoadingNotices) {
					return;
				}

				this.isLoadingNotices = true;

				if (isRefresh) {
					this.noticePageNum = 1;
					this.noticeList = [];
					this.hasMoreNotices = true;
				}

				try {
					const params = {
						pageNum: this.noticePageNum,
						pageSize: this.noticePageSize
					};

					const res = await getRecruitNotice(params);

					if (res.code === 200) {
						const {
							rows,
							total
						} = res;

						if (isRefresh) {
							this.noticeList = rows || [];
						} else {
							this.noticeList = [...this.noticeList, ...(rows || [])];
						}

						this.totalNotices = total || 0;
						this.hasMoreNotices = this.noticeList.length < this.totalNotices;
					} else {
						uni.showToast({
							title: res.msg || '获取公告数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载公告数据失败', error);
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.isLoadingNotices = false;
					this.isRefreshingNotices = false;
				}
			},

			// 刷新公告列表
			refreshNotices() {
				this.isRefreshingNotices = true;
				this.fetchNoticeList(true);
			},

			// 加载更多公告
			loadMoreNotices() {
				if (!this.hasMoreNotices || this.isLoadingNotices) {
					return;
				}

				this.noticePageNum++;
				this.fetchNoticeList();
			},

			// 跳转到公告详情
			goToNoticeDetail(item) {
				uni.navigateTo({
					url: `/pagesA/recruitNotice/detail?noticeId=${item.noticeId}`
				});
			},

			// 获取公司类型文本
			getCompanyTypeText(value) {
				if (!value && value !== 0) return '未知';
				const dictValue = String(value);
				const dictItem = this.companyTypeDict.find(item => item.dictValue === dictValue);
				return dictItem ? dictItem.dictLabel : '未知';
			},

			// 获取学历文本
			getDegreeText(value) {
				if (!value && value !== 0) return '不限';
				const dictValue = String(value);
				const dictItem = this.degreeTypeDict.find(item => item.dictValue === dictValue);
				return dictItem ? dictItem.dictLabel : '不限';
			},

			// 获取状态文本
			getStatusText(value) {
				if (!value && value !== 0) return '未知状态';
				const dictValue = String(value);
				const dictItem = this.applyStatusDict.find(item => item.dictValue === dictValue);
				return dictItem ? dictItem.dictLabel : '未知状态';
			},

			// 获取状态样式类
			getStatusClass(value) {
				const classMap = {
					3: 'status-upcoming', // 即将报名
					1: 'status-ongoing', // 正在报名
					2: 'status-ending', // 即将截止
					4: 'status-ended' // 结束报名
				}
				return classMap[value] || ''
			},

			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '--';
				const date = new Date(dateStr);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
			},

			// 加载字典数据
			async loadDictData() {
				try {
					// 并行加载所有字典数据
					const [companyTypeRes, degreeTypeRes, applyStatusRes] = await Promise.all([
						getDicts(this.companyTypeDictType),
						getDicts(this.degreeTypeDictType),
						getDicts(this.applyStatusDictType)
					]);

					// 设置字典数据
					if (companyTypeRes.code === 200) {
						this.companyTypeDict = companyTypeRes.data;
					}

					if (degreeTypeRes.code === 200) {
						this.degreeTypeDict = degreeTypeRes.data;
					}

					if (applyStatusRes.code === 200) {
						this.applyStatusDict = applyStatusRes.data;
					}
				} catch (error) {
					console.error('加载字典数据失败', error);
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f7fa;
	}

	.container {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		padding-top: calc(var(--status-bar-height) + 120rpx);
		/* 使用calc()函数正确计算状态栏高度加上额外间距 */
	}

	/* 固定区域样式 */
	.fixed-area {
		position: fixed;
		top: calc(var(--status-bar-height) + 120rpx);
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #f5f7fa;
	}

	/* 轮播图会占满顶部 */

	/* 轮播图样式 */
	.banner-swiper {
		width: 100%;
		height: 360rpx;
	}

	.banner-item {
		position: relative;
		width: 100%;
		height: 100%;
	}

	.banner-image {
		width: 100%;
		height: 100%;
		border-radius: 0 0 20rpx 20rpx;
	}

	.banner-title {
		position: absolute;
		left: 40rpx;
		bottom: 40rpx;
		display: flex;
		flex-direction: column;
		z-index: 2;
	}

	.banner-title-text {
		font-size: 40rpx;
		font-weight: bold;
		color: #ffffff;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
		margin-bottom: 8rpx;
	}

	.banner-subtitle {
		font-size: 28rpx;
		color: #ffffff;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
	}

	/* 核心功能区块样式 */
	.feature-section {
		display: flex;
		justify-content: space-between;
		padding: 24rpx 20rpx;
		background-color: #ffffff;
		margin: -20rpx 24rpx 24rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
		position: relative;
		z-index: 2;
	}

	.feature-item {
		width: 33%;
		position: relative;
	}

	.feature-button {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: transparent;
		padding: 0;
		margin: 0;
		line-height: normal;
		border: none;
		box-shadow: none;
	}

	.feature-button::after {
		border: none;
	}

	.feature-icon {
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 16rpx;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.08);
		transition: all 0.2s ease;
		position: relative;
	}

	.icon-wrapper {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.feature-button:active .feature-icon {
		transform: scale(0.95);
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
	}

	.feature-icon .iconfont {
		font-size: 44rpx;
		color: #fff;
	}

	.feature-emoji {
		font-size: 40rpx;
	}

	.feature-content {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.job-icon {
		background: #4285f4;
	}

	.job-icon .iconfont {
		color: #ffffff;
	}

	.template-icon {
		background: #4285f4;
	}

	.template-icon .iconfont {
		color: #ffffff;
	}

	.interview-icon {
		background: #4285f4;
	}

	.interview-icon .iconfont {
		color: #ffffff;
	}

	.feature-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 4rpx;
	}

	.feature-desc {
		font-size: 22rpx;
		color: #888;
	}

	/* 内容区域样式 */
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 90rpx;
		background: #fff;
		margin: 0 8rpx;
		border-radius: 16rpx 16rpx 0 0;
		border-bottom: 1rpx solid #eee;
		padding: 0 20rpx;
		position: relative;
	}

	.section-header::before {
		content: '';
		position: absolute;
		left: 20rpx;
		top: 50%;
		transform: translateY(-50%);
		width: 6rpx;
		height: 32rpx;
		background: #409EFF;
		border-radius: 3rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		padding-left: 16rpx;
	}

	.section-more {
		font-size: 26rpx;
		color: #409EFF;
		display: flex;
		align-items: center;
	}

	.section-more .iconfont {
		font-size: 24rpx;
		margin-left: 4rpx;
	}

	/* 可滚动内容区域 */
	.scrollable-content {
		flex: 1;
		margin-top: calc(360rpx + 220rpx + 110rpx);
		/* 调整顶部边距 */
		padding-bottom: 20rpx;
		/* 底部添加一些间距 */
		width: 100%;
		/* 确保占满整个宽度 */
	}

	.content-list {
		height: calc(100vh - 360rpx - 220rpx - 88rpx - var(--status-bar-height) - 120rpx);
		background: #fff;
		margin: 0 3rpx;
		border-radius: 0 0 16rpx 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		padding-top: 10rpx;
		/* 列表内容顶部添加一些内边距 */
		width: 100%;
		/* 进一步减小边距，使列表更宽 */
	}



	.status-upcoming {
		background-color: rgba(64, 158, 255, 0.1);
		color: #409EFF;
	}

	.status-ongoing {
		background-color: rgba(103, 194, 58, 0.1);
		color: #67C23A;
	}

	.status-ending {
		background-color: rgba(230, 162, 60, 0.1);
		color: #E6A23C;
	}

	.status-ended {
		background-color: rgba(245, 108, 108, 0.1);
		color: #F56C6C;
	}

	/* 公告卡片样式 */
	.notice-card {
		padding: 20rpx 16rpx;
		border-bottom: 1rpx solid #eee;
		position: relative;
		width: 100%;
		box-sizing: border-box;
		overflow: visible;
	}

	.notice-card:last-child {
		border-bottom: none;
	}

	.notice-card:active {
		background-color: #f9f9f9;
	}

	.notice-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 14rpx;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		padding-right: 4rpx;
		word-break: break-all;
	}

	.notice-info {
		margin-top: 16rpx;
	}

	.notice-tags-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.notice-time {
		font-size: 22rpx;
		color: #888;
		background-color: #f8f8f8;
		padding: 4rpx 10rpx;
		border-radius: 4rpx;
		margin-right: 8rpx;
	}

	.notice-status {
		font-size: 22rpx;
		padding: 4rpx 12rpx;
		border-radius: 6rpx;
		font-weight: normal;
	}

	.notice-detail {
		display: flex;
		flex-direction: column;
		margin-bottom: 10rpx;
	}

	.notice-detail-item {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 4rpx;
	}

	.notice-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 8rpx;
	}

	.notice-tag {
		font-size: 20rpx;
		padding: 2rpx 8rpx;
		border-radius: 4rpx;
		background: #f5f5f5;
		color: #666;
		margin-bottom: 4rpx;
		white-space: nowrap;
		max-width: 100%;
	}

	.status-upcoming {
		background-color: rgba(64, 158, 255, 0.1);
		color: #409EFF;
	}

	.status-ongoing {
		background-color: rgba(103, 194, 58, 0.1);
		color: #67C23A;
	}

	.status-ending {
		background-color: rgba(230, 162, 60, 0.1);
		color: #E6A23C;
	}

	.status-ended {
		background-color: rgba(245, 108, 108, 0.1);
		color: #F56C6C;
	}

	/* 加载更多和空状态提示 */
	.loading-more {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60rpx 0;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
</style>